var resultData = null;

$(function() {
    
    var user = JSON.parse(GetRequest().param).user;
     
    $("#breadcrumb").html(JSON.parse(GetRequest().param).breadcrumb)
        //加载layui模块
    layui.use(['laydate', 'form', 'table', 'laytpl'], function() {
        var laydate = layui.laydate,
            form = layui.form,
            table = layui.table,
            laytpl = layui.laytpl;
        //渲染时间插件
        laydate.render({
            elem: '#startTime'
        })
        laydate.render({
                elem: '#endTime',
            })
            //初始化页面
        $(document).ready(function() {
            queryData();
           

            table.render({
                elem: '#table',
                height: 'full-200',
                data: resultData,
                cols: [
                    [ //表头
                        { field: 'GoodsCode', title: '物品代码', templet: '<div><span title="{{d.GoodsCode}}">{{d.GoodsCode}}</span></div>', width: 100, },
                        { field: 'GoodsName', title: '物品名称', templet: '<div><span title="{{d.GoodsName}}">{{d.GoodsName}}</span></div>', width: 100 },
                        { field: 'GoodsSpec', title: '规格型号', templet: '<div><span title="{{d.GoodsSpec}}">{{d.GoodsSpec}}</span></div>', width: 100 },
                        { field: 'BoxUnit', title: '计量单位', width: 100 },
                        { field: 'WarnValue', title: '警戒低值', width: 100, templet: '#jjzTpl' },
                        { field: 'Status', title: '状态', width: 80 },
                        { field: 'UserName', title: '录入人', width: 100 },
                        { field: 'InputTime', title: '录入时间', width: 160, templet: '<div><span title="{{d.InputTime}}">{{d.InputTime==null||d.InputTime==undefined?"":d.InputTime}}</span></div>' },
                        { field: 'UpdateUserName', title: '修改人', width: 100 },
                        { field: 'UpdateTime', title: '修改时间', width: 160, templet: '<div><span title="{{d.UpdateTime}}">{{d.UpdateTime==null||d.UpdateTime==undefined?"":d.UpdateTime}}</span></div>' },
                        //          ,{field: 'jjz', title: '警戒低至',width: 160, templet: '#jjzTpl', sort: true}
                        { fixed: 'right', title: '操作', align: 'center', toolbar: '#bar' }
                    ]
                ],
                done: function() {
                    $(".layui-table-main table tbody").append('<tr><td><input id="showdialog" style="width:90px;" type="text" class="layui-input"></td></tr>')
                }
            })
        })

        if (resultData.length == 0) {
            reloadPageTableWithNoData();
        }

        //查询按钮的事件，以及查询的参数
        form.on('submit(search)', function(data) {
            //      console.log($(data.form).serialize());
            queryData();
            if (resultData.length == 0) {
                reloadPageTableWithNoData();
            } else {
                reloadPageTable();
            }

            return false; //必须写
        });
        //返回按钮绑定事件
        $("#back").click(function() {
            parent.showMenuFn();
            parent.$('#main').empty();
        })

        //监听工具条（保存，修改，删除等操作）
        table.on('tool(tabledata)', function(obj) { //注：tool是工具条事件名，tabledata是lay-filter="对应的值"
            var data = obj.data; //获得当前行数据
             
            var layEvent = obj.event; //获得 lay-event 对应的值
            //      if(layEvent === 'detail'){ //查看
            ////        console.log("查看")
            //        console.log(data)
            //      } else if(layEvent === 'del'){ //删除
            //        layer.confirm('真的删除行么', function(index){
            //          console.log(data.id);
            //          obj.del(); //删除对应行（tr）的DOM结构，并更新缓存
            //          layer.close(index);
            //          //向服务端发送删除指令
            //          // $.ajax({
            //          //
            //          // })
            //        });
            //      } else if(layEvent === 'edit'){ //编辑
            //        console.log("编辑");
            //      }
            var savedata = {
                "BillSN": data.BillSN,
                "GoodsID": data.GoodsID,
                "GoodsCode": data.GoodsCode,
                "WarnType": "1",
                "WarnValue": data.WarnValue,
                "UserID": data.UserID,
                "InputTime": new Date(data.InputTime).format("yyyy-MM-dd hh:mm:ss"),
                "UpdateUserID": data.UpdateUserID,
                "UpdateTime": "",
                "DeptAccountID": JSON.parse(localStorage.getItem("deptInfo")).DeptAccountID
            }
            if (layEvent === 'save') {
                
                if (data.UserID != "" && data.UserID != null && data.UserID != undefined) {
                    var params = {
                        className: 'TwoLevelStockManager',
                        method: 'ModifyStockWarning',
                        stockWarningInfo: JSON.stringify(savedata),
                        userID: user.Ygid
                    }
                    $.ajax({
                        type: "post",
                        url: getRootPath() + 'api/sendPostRequest',
                        dataType: "json",
                        contentType: 'application/json',
                        data: JSON.stringify(params),
                        async: false,
                        success: function(data) {
                            if (data.issuccess == 0) {
                                layer.msg('保存成功！', { time: 1000 });
                                 

                                $("#startTime").val("");
                                $("#endTime").val("");
                                $("#goodname").val("");
                                $("#status").val("2");

                                queryData();
                                table.reload("table", {
                                    data: resultData
                                })
                            } else {
                                layer.msg('保存失败！', { time: 1000 });
                            }
                        },
                        error: function(data) {
                            console.log(data.message)
                        }
                    })
                } else {
                    var params = {
                        className: 'TwoLevelStockManager',
                        method: 'InputStockWarning',
                        stockWarningInfo: JSON.stringify(savedata),
                        userID: user.Ygid
                    }
                    $.ajax({
                        type: "post",
                        url: getRootPath() + 'api/sendPostRequest',
                        dataType: "json",
                        contentType: 'application/json',
                        data: JSON.stringify(params),
                        async: false,
                        success: function(data) {
                            if (data.issuccess == 0) {
                                layer.msg('保存成功！', { time: 1000 });
                                 

                                $("#startTime").val("");
                                $("#endTime").val("");
                                $("#goodname").val("");
                                $("#status").val("2");

                                queryData();
                                reloadPageTable();
                            } else {
                                layer.msg('保存失败！', { time: 1000 });
                            }
                        },
                        error: function(data) {
                            console.log(data.message)
                        }
                    })
                }

            }
            //      else if(layEvent === 'edit'){
            //    	  if(data.UserID==""||data.UserID==null||data.UserID==undefined){
            //    		  layer.msg('修改失败，请选择保存按钮！',{time:1000});
            //    		  return;
            //    	  }
            //    	  var params = {
            //  				className : 'TwoLevelStockManager',
            //  				method : 'ModifyStockWarning',
            //  				stockWarningInfo : JSON.stringify(savedata),
            //  				userID : user.Ygid
            //  			}
            //      	  $.ajax({
            //      			type : "post",
            //      			url : getRootPath() + 'api/sendPostRequest',
            //      			dataType : "json",
            //      			contentType: 'application/json',
            //      			data : JSON.stringify(params),
            //      			async : false,
            //      			success : function(data) {
            //      				layer.msg('修改成功！',{time:1000});
            //      				console.log(data.result)
            //      				
            //      				$("#startTime").val("");
            //					$("#endTime").val("");
            //					$("#goodname").val("");
            //					$("#status").val("2");
            //      				
            //      				queryData();
            //			    	table.reload("table",{
            //			    		data:resultData
            //			    	})
            //      			},
            //      			error : function(data) {
            //      				console.log(data.message)
            //      			}
            //      		})
            //      }
            else if (layEvent === 'open') {
                if (data.Status == "" || data.Status == null || data.Status == undefined) {
                    layer.msg('数据未保存,无法进行此操作', { time: 2000 });
                    return;
                }
                var params = {
                    className: 'TwoLevelStockManager',
                    method: 'UpdateStockWarningStatus',
                    billSN: data.BillSN,
                    status: "1"
                }
                $.ajax({
                    type: "post",
                    url: getRootPath() + 'api/sendPostRequest',
                    dataType: "json",
                    contentType: 'application/json',
                    data: JSON.stringify(params),
                    async: false,
                    success: function(data) {
                        if (data.issuccess == 0) {
                            layer.msg('已启用！', { time: 1000 });
                             

                            queryData();
                            table.reload("table", {
                                data: resultData
                            })
                        } else {
                            layer.msg('启用失败！', { time: 1000 });
                        }
                    },
                    error: function(data) {
                        console.log(data.message)
                    }
                })
            } else if (layEvent === 'unopen') {
                if (data.Status == "" || data.Status == null || data.Status == undefined) {
                    layer.msg('数据未保存,无法进行此操作', { time: 2000 });
                    return;
                }
                var params = {
                    className: 'TwoLevelStockManager',
                    method: 'UpdateStockWarningStatus',
                    billSN: data.BillSN,
                    status: "0"
                }
                $.ajax({
                    type: "post",
                    url: getRootPath() + 'api/sendPostRequest',
                    dataType: "json",
                    contentType: 'application/json',
                    data: JSON.stringify(params),
                    async: false,
                    success: function(data) {
                        if (data.issuccess == 0) {
                            layer.msg('已停用！', { time: 1000 });
                          

                            queryData();
                            table.reload("table", {
                                data: resultData
                            })
                        } else {
                            layer.msg('停用失败！', { time: 1000 });
                        }
                    },
                    error: function(data) {
                        console.log(data.message)
                    }
                })
            } else if (layEvent === 'del') {
                layer.confirm('真的删除行么', function(index) {
                    //            console.log(data.id);

                    if (data.BillSN != null) {
                        //              向服务端发送删除指令
                        var params = {
                            className: 'TwoLevelStockManager',
                            method: 'DeleteStockWarning',
                            billSN: data.BillSN
                        }
                        $.ajax({
                            type: "post",
                            url: getRootPath() + 'api/sendPostRequest',
                            dataType: "json",
                            contentType: 'application/json',
                            data: JSON.stringify(params),
                            async: false,
                            success: function(data) {
                                if (data.issuccess == 0) {
                                    obj.del(); //删除对应行（tr）的DOM结构，并更新缓存
                                    layer.close(index);

                                    layer.msg('删除成功！', { time: 1000 });
                                    console.log(data.result)

                                    $("#startTime").val("");
                                    $("#endTime").val("");
                                    $("#goodname").val("");
                                    $("#status").val("2");

                                    queryData();
                                    if (resultData.length == 0) {
                                        reloadPageTableWithNoData();
                                    } else {
                                        reloadPageTable();
                                    }

                                } else {
                                    layer.msg('删除失败！', { time: 1000 });
                                }
                            },
                            error: function(data) {
                                console.log(data.message)
                            }
                        })
                    } else {
                        obj.del(); //删除对应行（tr）的DOM结构，并更新缓存
                        layer.close(index);
                        layer.msg('删除成功！', { time: 1000 });
                    }

                });
            } else {

            }
        });

        //    $("body").on("click","#showdialog",function(){
        //      layer.open({
        //        type: 2,
        //        area: ['900px', '400px'],
        //        fixed: false, //不固定
        //        maxmin: false,
        //        title:'物品查询',
        //        content: '../view/common.html'
        //      });
        //    })
        $("body").on("keydown", "#showdialog", function(e) {
            if (e.keyCode == 13) {
                ////        	console.log("1234567890")
                //            //to-do when click Enter Key
                //        	table.cache.table.push({
                //        		GoodsID:"LL019070001010",
                //        		GoodsCode:"BB001013000000",
                //        		GoodsName:"自动折纱布机",
                //        		GoodsSpec:"",
                //        		BoxUnit:"台",
                //        		WarnValue:"0"
                //        	});
                //        	var data = table.cache.table;
                //        	table.reload("table",{
                //        		data:data
                //        	})
                parent.$('#goodsSelectWrap').load(getRootPath() + 'new/view/GoodsQuery.html')
            }
        });
        //获取当前行数据
        getindex = function(idx, value) {
            //      console.log(table)
            //      console.log(table.cache.table[idx]);
            //      console.log(value)
            table.cache.table[idx - 1].WarnValue = value;
        }


        window.addEventListener('message', function(e) {
            if (e.source != window.parent) return;
            var newBillData = e.data
                //    	console.log(e.data)
                //    	console.log(table.cache.table)
                //    	resultData = table.cache.table;

            for (var i = 0; i < resultData.length; i++) {
                if (resultData[i].GoodsCode == newBillData.GoodsCode) {
                    layer.msg('所选物品已在维护列表，请勿重复添加！', { time: 2000 });
                    return;
                }
            }

            resultData.push({
                GoodsID: newBillData.GoodsID,
                GoodsCode: newBillData.GoodsCode,
                GoodsName: newBillData.GoodsName,
                GoodsSpec: newBillData.GoodsSpec,
                BoxUnit: newBillData.BoxUnit,
                WarnValue: "0"
            });
            reloadPageTable();
        })


        function reloadPageTableWithNoData() {
            table.reload("table", {
                data: [{ GoodsCode: "", GoodsName: "", GoodsSpec: "", BoxUnit: "", WarnValue: "", Status: "", UserID: "", InputTime: "", UpdateUserID: "", UpdateTime: "" }],
                cols: [
                    [ //表头
                        { field: 'GoodsCode', title: '物品代码', templet: '#input', width: 100, },
                        { field: 'GoodsName', title: '物品名称', width: 100, templet: "#bar0" },
                        { field: 'GoodsSpec', title: '规格型号', width: 100, templet: "#bar0" },
                        { field: 'BoxUnit', title: '计量单位', width: 100 },
                        { field: 'WarnValue', title: '警戒低值', width: 100, templet: "#bar0" },
                        { field: 'Status', title: '状态', width: 80 },
                        { field: 'UserName', title: '录入人', width: 100 },
                        { field: 'InputTime', title: '录入时间', width: 160 },
                        { field: 'UpdateUserName', title: '修改人', width: 100 },
                        { field: 'UpdateTime', title: '修改时间', width: 160 },
                        { fixed: 'right', title: '操作', align: 'center', toolbar: "#bar0" }
                    ]
                ],
                done: function(res, curr, count) {

                }
            })
        }

        function reloadPageTable() {
            table.reload("table", {
                data: resultData,
                cols: [
                    [ //表头
                        { field: 'GoodsCode', title: '物品代码', templet: '<div><span title="{{d.GoodsCode}}">{{d.GoodsCode}}</span></div>', width: 100, },
                        { field: 'GoodsName', title: '物品名称', templet: '<div><span title="{{d.GoodsName}}">{{d.GoodsName}}</span></div>', width: 100 },
                        { field: 'GoodsSpec', title: '规格型号', templet: '<div><span title="{{d.GoodsSpec}}">{{d.GoodsSpec}}</span></div>', width: 100 },
                        { field: 'BoxUnit', title: '计量单位', width: 100 },
                        { field: 'WarnValue', title: '警戒低值', width: 100, templet: '#jjzTpl' },
                        { field: 'Status', title: '状态', width: 80 },
                        { field: 'UserName', title: '录入人', width: 100 },
                        { field: 'InputTime', title: '录入时间', width: 160 },
                        { field: 'UpdateUserName', title: '修改人', width: 100 },
                        { field: 'UpdateTime', title: '修改时间', width: 160 },
                        { fixed: 'right', title: '操作', align: 'center', toolbar: '#bar' }
                    ]
                ],
                done: function() {
                    $(".layui-table-main table tbody").append('<tr><td><input id="showdialog" style="width:90px;" type="text" class="layui-input"></td></tr>')
                }
            })
        }


    })

})

/**
 * 查询数据
 */
function queryData() {
    var condition = {
        "Conditions": [{
            "ColumnName": "WarnType",
            "FullString": null,
            "Oper": "Equal",
            "Value": "1",
            "Type": "String"
        }, {
            "ColumnName": "a.yxbz",
            "FullString": null,
            "Oper": "Equal",
            "Value": "1",
            "Type": "String"
        }, {
            "ColumnName": "a.DeptAccountID",
            "FullString": null,
            "Oper": "Equal",
            "Value": JSON.parse(localStorage.getItem("deptInfo")).DeptAccountID,
            "Type": "String"
        }],
        "Type": "AND"
    };
    if ($("#goodname").val().trim() != "") {
        condition.Conditions.push({
            "ColumnName": "WZ_Expiry_Stock_Warn.GoodsName",
            "FullString": null,
            "Oper": "Like",
            "Value": "%" + $("#goodname").val() + "%",
            "Type": "String"
        })
    }
    if ($("#startTime").val() != "") {
        condition.Conditions.push({
            "ColumnName": "InputTime",
            "FullString": null,
            "Oper": "MoreOrEqual",
            "Value": $("#startTime").val(),
            "Type": "DateTime"
        })
    }
    if ($("#endTime").val() != "") {

        condition.Conditions.push({
            "ColumnName": "InputTime",
            "FullString": null,
            "Oper": "LessOrEqual",
            "Value": $("#endTime").val() + " 23:59:59",
            "Type": "DateTime"
        })
    }
    if ($("#status").val() != "2") {
        condition.Conditions.push({
            "ColumnName": "Status",
            "FullString": null,
            "Oper": "Equal",
            "Value": $("#status").val(),
            "Type": "String"
        })
    }

    var params = {
        className: 'TwoLevelStockManager',
        method: 'GetStockWarnings',
        condition: JSON.stringify(condition),
    }
    $.ajax({
        type: "post",
        url: getRootPath() + 'api/sendPostRequest',
        dataType: "json",
        contentType: 'application/json',
        data: JSON.stringify(params),
        async: false,
        success: function(data) {
            

            if (data.issuccess == 0) {
                resultData = JSON.parse(data.result);
                for (var i = 0; i < resultData.length; i++) {
//                    if (resultData[i].InputTime != null) {
//                        resultData[i].InputTime = "";
//                    }
//                    if (resultData[i].UpdateTime != null) {
//                        resultData[i].UpdateTime = "";
//                    }
                    if (resultData[i].Status) {
                        resultData[i].Status = "启用";
                    } else {
                        resultData[i].Status = "停用";
                    }
                }
                //				var html = "";
                //				for (var i = 0; i < JSON.parse(data.result).length; i++) {
                //					html += '<tr>' + '<td>LL19070001010</td>'
                //							+ '<td>活检针（18G*150cm）</td>'
                //							+ '<td>活检针（18G*150cm）</td>' + '<td>只</td>' + '<td>'
                //							+ '<input type="number">' + '</td>' + '<td>张三</td>'
                //							+ '<td>2018-07-11</td>' + '<td>张三</td>'
                //							+ '<td>2018-07-11</td>' + '<td>'
                //							+ '<button>保存</button>' + '<button>修改</button>'
                //							+ '<button>启用</button>' + '<button>停用</button>'
                //							+ '<button>删除</button>' + '</td>' + '</tr>';
                //				}
                //				$("#dataBody").append(html);
            } else {
                layer.msg('查询失败！', { time: 3000 });
            }
        },
        error: function(data) {
            console.log(data.message)
        }
    })
}